package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.mulityItemAdapter;
import cn.acewill.yxd.yunxundian.model.MailBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.SimpleSpinnerOption;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SendMailActivity;

/**
 * Created by XXX on 2017/12/20.
 */

public class ScheduleMailActivity extends BaseActivity implements View.OnClickListener{

    private TextView selReceiver,selCCReceiver;
    private EditText mailContent,otherReceiver;
    private List<MailBean> mailList;
    private String diyiString,dierString;
    private int whatreceiver = 0;
    private List<String> selectList;
    private String year,month;
    private ProgressDialog progressDialog;
    private List<SimpleSpinnerOption> selReList;
    private List<SimpleSpinnerOption> selCcList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_maill_view);
        initView();
    }
    private void initView(){
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myToolBar.setNavigationIcon(R.mipmap.back);
        myToolBar.setTitle("");
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        year=getIntent().getStringExtra("year");
        month = getIntent().getStringExtra("month");
        selReceiver = (TextView) findViewById(R.id.selReceiver);
        selCCReceiver = (TextView) findViewById(R.id.selCCReceiver);
        mailContent = (EditText) findViewById(R.id.mailContent);
        Button sureBtn = (Button) findViewById(R.id.sureBtn);
        otherReceiver = (EditText) findViewById(R.id.otherReceiver);
        selCCReceiver.setOnClickListener(this);
        selReceiver.setOnClickListener(this);
        sureBtn.setOnClickListener(this);
        mailListData();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.selReceiver:
                whatreceiver=1;
                if (TextUtils.isEmpty(diyiString)){
                    BaseActivity.showAnimaDialog(this,"无收件人可选");
                }else{
                    List<SimpleSpinnerOption> diyiList = new ArrayList<>();
                    String diyi[] = diyiString.split(",");
                    for (String aDiyi : diyi) {
                        String as[] = aDiyi.split(":");
                        if (!TextUtils.isEmpty(as[0]) && !TextUtils.isEmpty(as[1])) {
                            //去掉分号
                            String mail = as[0].substring(1, as[0].length() - 1);
                            String name = as[1].substring(1, as[1].length() - 1);
                            SimpleSpinnerOption option = new SimpleSpinnerOption();
                            option.setName(name);
                            option.setValue(mail);
                            diyiList.add(option);
                        }
                    }

                    startActivityForResult(new Intent(ScheduleMailActivity.this,MultMailActivity.class)
                            .putExtra("target",whatreceiver).putExtra("str", JSON.toJSONString(diyiList)).putExtra("selects",JSON.toJSONString(selReList)),101);
//                    creatDialog(diyiList);
                }
                break;
            case R.id.selCCReceiver:
                whatreceiver=2;
                if (TextUtils.isEmpty(dierString)){
                    BaseActivity.showAnimaDialog(this,"无收件人可选");
                }else{
                    List<SimpleSpinnerOption> dierList = new ArrayList<>();
                    String dier[] = dierString.split(",");
                    for (String aDier : dier) {
                        String as[] = aDier.split(":");
                        if (!TextUtils.isEmpty(as[0]) && !TextUtils.isEmpty(as[1])) {
                            String mail = as[0].substring(1, as[0].length() - 1);
                            String name = as[1].substring(1, as[1].length() - 1);
//                            dierList.add(mail+":"+name);
                            SimpleSpinnerOption option = new SimpleSpinnerOption();
                            option.setName(name);
                            option.setValue(mail);
                            dierList.add(option);
                        }
                    }
                    startActivityForResult(new Intent(ScheduleMailActivity.this,MultMailActivity.class)
                            .putExtra("target",whatreceiver).putExtra("str", JSON.toJSONString(dierList)).putExtra("selects",JSON.toJSONString(selCcList)),101);
                }
                break;
            case R.id.sureBtn:
                String Smail = selReceiver.getText().toString().trim();
                if (TextUtils.isEmpty(Smail)){
                    BaseActivity.showAnimaDialog(this,"请选择收件人");
                    return;
                }
                String content = mailContent.getText().toString().trim();
                String ccStr = selCCReceiver.getText().toString();
                if (ccStr.equals("点击选择")){
                    ccStr="";
                }
                String add = otherReceiver.getText().toString().trim();
                try {
                    sendMail(Smail,content,add,ccStr);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
    //获取收件人
    public void mailListData(){
        Map<String,String> map = new HashMap<>();
        map.put("task","loadeMailList");
        map.put("empid", MainActivity.id+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String res[] = result.split("\\|");
                    if (res[0].equals("200")){
                        Gson gson  = new Gson();
                        Type typeList=new TypeToken<ArrayList<MailBean>>(){
                        }.getType();
                        mailList= gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                        //只有一条数据
                        MailBean mail = mailList.get(0);
                        //拆分数据
                        if (mail.getDiyi().charAt(0)=='{'){
                            diyiString= mail.getDiyi().replace("{","").replace("}","").replace("","");
                        }
                        if (mail.getDier().charAt(0)=='{'){
                            dierString=mail.getDier().replace("{","").replace("}","");
                        }
                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(ScheduleMailActivity.this,"网络失去连接...");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void creatDialog(List<String> list){
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogview = inflater.inflate(R.layout.mulity_listview, null);
        ListView listview= (ListView) dialogview.findViewById(R.id.X_listview);
       final mulityItemAdapter adapter = new mulityItemAdapter(this,list);
        listview.setAdapter(adapter);
        selectList=new ArrayList<>();
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSecletion(position);
                adapter.notifyDataSetChanged();
                String str = (String) parent.getItemAtPosition(position);
                if (selectList.size()==0){
                    selectList.add(str);
                }else{
                    for (int i=0;i<selectList.size();i++){
                        if (selectList.get(i).equals(str)){
                            selectList.remove(i);
                            return;
                        }
                    }
                    selectList.add(str);
                }
            }
        });
        listview.setItemsCanFocus(true);
        listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("请选择收件人");
        builder.setView(dialogview);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (selectList.size()<=0){
                    if (whatreceiver==2){
                        selCCReceiver.setText("点击选择");
                    }
                    return;
                }
                String str="";
                for (int i=0;i<selectList.size();i++){
                    String thstr[] = selectList.get(i).split(":");
                    str=str+thstr[0]+",";
                }
                str=str.substring(0,str.length()-1);
                if (whatreceiver==1){
                    selReceiver.setText(str);
                }else{
                    selCCReceiver.setText(str);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }

    public void sendMail(String tomail,String body,String addm,String tocc) throws IOException {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在发送");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        HashMap<String,String> map = new HashMap<>();
        map.put("task","mailSchedule");
        map.put("empid",MainActivity.id+"");
        map.put("year",year);
        map.put("month",month);
        map.put("mailtoStr",tomail);
        map.put("mailBody",body);
        map.put("addMail",addm);
        map.put("toCCList",tocc);
        OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
            @Override
            public void onSuccess(String result) {
                String[] str = result.split("\\|");
                progressDialog.dismiss();
                if (str[0].equals("200")){
                    showToast(ScheduleMailActivity.this,"邮件已发送");
                    finish();
                }else{
                    showToast(ScheduleMailActivity.this,"邮件发送失败");
                }

            }

            @Override
            public void onFailture() {
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                showToast(ScheduleMailActivity.this,"邮件发送失败");
            }
        },map);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Gson gson=new Gson();
        Type typeList = new TypeToken<ArrayList<SimpleSpinnerOption>>() {
        }.getType();
        switch (requestCode){
            case 101:
                if (data!=null){
                    String str = data.getStringExtra("selectStr");
                    List<SimpleSpinnerOption> options = gson.fromJson(pubClass.convertToArrayJsonNormal(str),typeList);
//                    if (options!=null&&options.size()>0){
//                        selReList = new ArrayList<>();
//                        selReList = options;
//                        String value = "";
//                        for (SimpleSpinnerOption option: options) {
//                            value+=option.getValue()+",";
//                        }
//                        selReceiver.setText(value.substring(0,value.length()-2));
//                    }
                    if (options!=null&&options.size()>0){
                        String value = "";
                        for (SimpleSpinnerOption option: options) {
                            if (option.isChecked()){
                                value+=option.getValue()+",";
                            }
                        }
                        if (!TextUtils.isEmpty(value)){
                            if (whatreceiver==1){
                                selReceiver.setText(value.substring(0,value.length()-1));
                                selReList = options;
                            }else{
                                selCCReceiver.setText(value.substring(0,value.length()-1));
                                selCcList = options;
                            }

                        }else{
                            if (whatreceiver==1){
                                selReceiver.setText("点击选择");
                                if(selReList!=null&&selReList.size()>0){
                                    selReList.clear();
                                }

                            }else{
                                selCCReceiver.setText("点击选择");
                                if (selReList!=null&&selReList.size()>0){
                                    selCcList.clear();
                                }
                            }
                        }
                    }
                }
                break;
        }
    }
}
